package com.qst.controller;

import com.qst.pojo.Employee;
import com.qst.service.LoginService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;

/**
 * @author Eumenides.
 * @create 2021-06-17 10:24
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService service;

    /**
     * @return java.lang.String
     * @Param [username, password, session, request]
     * @author Eumenides
     * 登录逻辑
     */
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, HttpSession session, HttpServletRequest request) {
//        Employee employee = service.login("admin", "123456");
//        session.setAttribute("curUser", employee);
//        return "redirect:/myMeeting";
                if(username == null || password == null) {
            request.setAttribute("error", "请输入用户名和密码");
            return "../index";
        }
        //调用service层实现业务逻辑
        Employee employee = service.login(username, password);
        //根据业务逻辑与前端进行交互
        if (employee != null && employee.getStatus() == 1) { // 用户名密码正确且已经审批，则登陆成功
            //保存当前用户信息
            session.setAttribute("curUser", employee);
            // 跳转到notifications.jsp
            return "redirect:/myMeeting";
        } else if (employee == null) {// 用户名密码不正确，登录不成功
            // 给出提示信息
            request.setAttribute("error", "用户不存在或密码有误");
            // 返回到登录页面
            return "../index";
        } else {
            request.setAttribute("error", "用户未审批或者审批不通过，请联系管理员处理");
            return "../index";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("curUser");
        System.out.println("logout success");
        return "redirect:/";
    }
}
